package com.wjk.cms.service.impl;

import com.auth0.jwt.JWT;
import com.wjk.cms.dao.UserRepository;
import com.wjk.cms.pojo.User;
import com.wjk.cms.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Service
public class SecurityServiceImpl implements SecurityService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public Long getCurrentUserId() {
        String tokenUserId = getTokenUserId();
        if (tokenUserId == null) {
            return null;
        }
        Long userId = null;
        try {
            userId = Long.valueOf(tokenUserId);
        } catch (Exception e) {
        }
        return userId;
//    return 1L;
    }

    @Override
    public User getCurrentUser() {
        Long userId = getCurrentUserId();
        return userId != null ? userRepository.findById(userId).orElse(null) : null;
    }



    private HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }

    private String getTokenUserId() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        String userId = null;
        try {
            String token = getRequest().getHeader("token");
            userId = JWT.decode(token).getAudience().get(0);
        } catch (Exception e) {
        }
        return userId;
    }

}
